import axios from 'axios'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import router from '../router'

const baseURL = 'http://localhost:40321/api'

// 创建 axios 实例
const request = axios.create({
  baseURL,
  withCredentials: true // 允许携带凭证
})

// 检查登录状态的函数
const checkLogin = () => {
  const userStore = useUserStore()
  if (!userStore.id) {
    ElMessage.warning('请先登录后再操作')
    router.push('/login')
    return false
  }
  return true
}

export function getChatHistory(userId) {
  if (!checkLogin()) return Promise.reject('未登录')
  
  return request.get(`/ai/history?userId=${userId}`)
}

export const sendChatMessage = async (chatId, text, userId) => {
  if (!checkLogin()) return Promise.reject('未登录')
  
  try {
    const response = await fetch(`${baseURL}/ai/chat?text=${encodeURIComponent(text)}&chatId=${chatId}&userId=${userId}`, {
      method: 'GET',
      headers: {
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache'
      },
      credentials: 'include'
    })
    return response.body
  } catch (error) {
    throw error.response?.data || error
  }
}

export async function getChatHistoryById(chatId) {
  if (!checkLogin()) return Promise.reject('未登录')
  
  const userStore = useUserStore()
  try {
    const response = await request.get(`/ai/history/${chatId}?userId=${userStore.id}`)
    return response.data
  } catch (error) {
    throw error.response?.data || error
  }
}

export const deleteChatApi = (chatId,userId) => {
  if (!checkLogin()) return Promise.reject('未登录')
  
  return request.delete(`/ai/chat/delete/${chatId}?userId=${userId}`)
}

